//
//  HomeViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/9.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
/// 首页
class HomeViewController: BaseViewController {
    
    private var headerView: HomeHeaderView!
    
    private var viewModel = YSGHomeViewModel()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.isHidden = true
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView()
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
        tableView.register(DoctorReserveCell.nibForCell(),
                           forCellReuseIdentifier: DoctorReserveCell.reuseIdentifier())
        tableView.register(YSGHomeBannerCell.nibForCell(),
                           forCellReuseIdentifier: YSGHomeBannerCell.reuseIdentifier())
        tableView.register(YSGWesternSearchCell.nibForCell(),
                           forCellReuseIdentifier: YSGWesternSearchCell.reuseIdentifier())
        tableView.register(YSGHomeDepartmentCell.nibForCell(),
                           forCellReuseIdentifier: YSGHomeDepartmentCell.reuseIdentifier())
        return tableView
    }()
    
    private lazy var navBarView = UINib.loadViewFrom(HomeNavBarView.self)
    
   
    
}

// MARK: - Life Cycle
extension HomeViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavBar()
        setupTableHeader()
        setupRefresh()

        view.backgroundColor = .white
        viewModel.updateClosure = { [weak self] error in
            DispatchQueue.main.async {
                self?.endRefresh()
                self?.headerView.isHidden = false
                self?.tableView.isHidden = false
            }
            
            guard let self = self else { return }
            
            if error != nil {
                HUDTool.showError(message: error)
            } else {
                DispatchQueue.main.async {
                    self.headerView.reloadData(with: self.viewModel)
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setNavClear()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        setNavWhite()
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
}

extension HomeViewController {
    private func setupNavBar() {
        
        let navBackView = UIImageView()
        navBackView.image = UIImage(named: "home_nav_back")
        navBackView.contentMode = .scaleToFill
        navBackView.backgroundColor  = .white
        view.addSubview(navBackView)
        navBackView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(navBarH + 256)
        }
        
        view.addSubview(navBarView)
        navBarView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(navBarH)
        }
        
        navBarView.handlerClosure = { [weak self] isSearch in
            if isSearch {
                self?.presentSearchVc()
            } else {
                HUDTool.show(message: "功能待开发")
            }
        }
    }
    
    private func setupTableHeader() {
        headerView = HomeHeaderView(with: self)
        headerView.frame = CGRect(x: 0, y: 0, width: screenW, height: 256)
        headerView.isHidden = true
        tableView.tableHeaderView = headerView
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(navBarView.snp.bottom)
        }
        if #available(iOS 15, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        headerView.viewTapped = { [weak self] type in
            switch type {
            case .registration:
                self?.registrationType()
            case .advisory:
                self?.moreDoctorList(.advisory)
            case .cloud:
                self?.cloudDoctorList(.cloud)
            case .team:
                self?.teamInquiryList()
            case .myopia:
                self?.pushWebController()
            case .nurse:
                self?.pushNurseAppointment()
            }
        }
    }
    
    private func setupRefresh() {
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
        
        tableView.mj_footer = noMoreDataFooter("没有更多推荐了")
    }
    
    private func endRefresh() {
        tableView.mj_header?.endRefreshing()
    }
    
    @objc private func loadData() {
        viewModel.getHomeData()
    }
}

// MARK: - Helpers
extension HomeViewController {
    private func presentSearchVc() {
        let resultVc = DoctorLIstResultViewController(doctorType: .all)
        navigationController?.pushViewController(resultVc, animated: true)
    }
    
    private func pushDoctorDetail(with vm: DoctorReserveRowViewModel) {
        let detailVc = DoctorDetailController(with: vm.doctorId)
        navigationController?.pushViewController(detailVc, animated: true)
    }
    
    private func pushSearchController() {
        let westernSearchVC = YSGWesternSearchController()
        navigationController?.pushViewController(westernSearchVC, animated: true)
    }
    
    private func reserveAdvisory(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .advisory)
        
        
        let adMedicalRecordsVC = AdMedicalRecordsController()
        adMedicalRecordsVC.doctorVm = doctorDetail
        navigationController?.pushViewController(adMedicalRecordsVC, animated: true)
    }
    
    private func reserveCloud(_ vm: DoctorReserveRowViewModel, type: DoctorType) {
        let model = DoctorDetail(id: vm.doctorId,
                                 deptId: vm.departmentId,
                                 docName: vm.doctorName,
                                 deptName: vm.department,
                                 hospitalName: vm.hospitalName,
                                 jobTitleName: vm.office,
                                 docGoodAtNames: vm.specialty,
                                 thumbnailUrl: vm.thumbnailUrl,
                                 score: vm.score.floatValue,
                                 fee: vm.fee,
                                 diagType: type.rawValue)
        let doctorDetail = DoctorDetailViewModel(model: model,
                                                 selectType: .cloud)
        let newCloudVc = NewCloudReserveController(with: doctorDetail)
        navigationController?.pushViewController(newCloudVc, animated: true)
    }
    
    private func pushWebController() {
        let webVc = ReportWebViewController(webType: .bannerAds)
        navigationController?.pushViewController(webVc, animated: true)
    }
    
    private func pushNurseAppointment() {
        let vc = YSGNurseAppointmentController()
        navigationController?.pushViewController(vc, animated: true)
    }
}

extension HomeViewController {
    @objc private func moreDoctorTap() {
        moreDoctorList(.all)
    }
    
    @objc private func moreDepartment() {
        moreDepartmentsList()
    }
    
    private func moreDepartmentsList() {
        let departmentsVc = YSGDepartmentListController()
        departmentsVc.title = "更多科室"
        navigationController?.pushViewController(departmentsVc, animated: true)
    }
    
    private func registrationType() {
        let vc = RegistrationTypeController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func moreDoctorList(_ type: DoctorType, departmentId: String = "", departmentName: String? = nil) {
        let doctorList = DoctorReserveController(with: type, departmentId: departmentId, departmentName: departmentName)
        navigationController?.pushViewController(doctorList, animated: true)
    }
    
    private func cloudDoctorList(_ type: DoctorType) {
        let cloudVc = DateReserveController(with: type)
        navigationController?.pushViewController(cloudVc, animated: true)
    }
    
    private func teamInquiryList() {
        let teamList = ESGTeamInquiryController()
        navigationController?.pushViewController(teamList, animated: true)
    }
    
    /// 跳转近视防控
    private func myopiaControlVc() {
        let myopiaVc = YSGMyopiaControlController()
        navigationController?.pushViewController(myopiaVc, animated: true)
    }
}

extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 3:
            return viewModel.doctorVm().numberOfRows
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGHomeDepartmentCell.reuseIdentifier(), for: indexPath) as! YSGHomeDepartmentCell
            cell.delegate = self
            cell.configure(with: viewModel.departmentVm())
            return cell
        case 3:
            let cell = tableView.dequeueReusableCell(withIdentifier: DoctorReserveCell.reuseIdentifier(),
                                                     for: indexPath) as! DoctorReserveCell
            cell.delegate = self
            let vm = viewModel.doctorVm().viewModel(of: indexPath)
            cell.configure(with: vm)
            return cell
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGHomeBannerCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGHomeBannerCell
            cell.configure(with: viewModel, target: self)
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGWesternSearchCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGWesternSearchCell
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 2:
            let header = UINib.loadViewFrom(HomeSectionHeader.self)
            header.makeUI(self, action: #selector(moreDepartment), type: .department)
            return header
        case 3:
            let header = UINib.loadViewFrom(HomeSectionHeader.self)
            header.makeUI(self, action: #selector(moreDoctorTap), type: .doctor)
            return header
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 2:
            return viewModel.departmentVm().cellHeight()
        case 3:
            let vm = viewModel.doctorVm().viewModel(of: indexPath)
            return vm.cellHeight()
        case 0:
            return viewModel.centerBannerVm().cellHeight
        default:
            return 36
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 2, 3: return 50
        default: return 16
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.section {
        case 1:
            pushSearchController()
        case 3:
            let vm = viewModel.doctorVm().viewModel(of: indexPath)
            pushDoctorDetail(with: vm)
        default:
            break
        }
    }
}

extension HomeViewController: DoctorReserveCellDelegate, YSGHomeDepartmentItemDelegate, BannerViewDelegate {
    func bannerView(_ bannerView: BannerView, didSelectedItemWith viewModel: YSGBannerCellViewModel) {
        let type = viewModel.model.jumpMode ?? .default
        switch type {
        case .default:
            // 先去掉近视防控的入口，1.3.3版本提交审核时带上
            /* 刘保军 2022/09/14 09:39
            @朱成龙- iOS 入口去掉
             */
//            myopiaControlVc()
            break
        case .web:
            pushBrowser(urlStr: viewModel.model.target ?? "")
        case .miniApp:
            pushMiniProgram(jsonStr: viewModel.model.target ?? "")
        default:
            break
        }
    }
    
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveCloud type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        let vm = viewModel.doctorVm().viewModel(of: indexPath)
        reserveCloud(vm, type: type)
    }
    
    func doctorReserveCell(_ cell: DoctorReserveCell, willReserveAdvisory type: DoctorType) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        let vm = viewModel.doctorVm().viewModel(of: indexPath)
        reserveAdvisory(vm, type: type)
    }
    
    func departmentItem(didSelectedWith vm: YSGDepartmentItemViewModel) {
        moreDoctorList(.all, departmentId: vm.model.id ?? "", departmentName: vm.model.name)
    }
    
    /// 跳转小程序
    private func pushMiniProgram(jsonStr: String) {
        
        guard let model = YSGJSModel.deserialize(from: jsonStr) else { return }
        
        let req = WXLaunchMiniProgramReq.object()
        req.userName = model.appid ?? ""//"gh_d792f5cc2936"//"gh_81cce4b0e0c4"
        req.path = model.url ?? ""
        req.miniProgramType = .release
        WXApi.send(req)
    }
    
    /// 跳浏览器
    private func pushBrowser(urlStr: String) {
        guard let url = URL(string: urlStr) else { return }
        
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}
